//
//  LoginVC.m
//  ImGuider
//
//  Created by llt on 2017/4/20.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "LoginVC.h"
#import "ResetPSWVC.h"
#import "RegisterVC.h"
#import <IQKeyboardManager.h>
#import <UMSocialCore/UMSocialCore.h>
#import "SelectCountryVC.h"


@interface LoginVC ()

@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;

@property (weak, nonatomic) IBOutlet UILabel *pswLabel;

@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UITextField *pswTF;

@property (weak, nonatomic) IBOutlet UIButton *countryBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *resetPSWBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contryBtnWidth;

@property (nonatomic, strong) Country *currentCountry;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerBtnBottom;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"11"];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [MobClick endLogPageView:@"11"];
}

- (void)setup {
    
    self.barBGAlpha = 0;
    self.customBarStyle = UIStatusBarStyleLightContent;
    
    self.view.backgroundColor = kThemeColor;
    self.title = MYLocalizedString(@"LOGIN_TITLE", nil);
    
    self.phoneLabel.text = MYLocalizedString(@"LOGIN_MOBILE", nil);
    self.pswLabel.text = MYLocalizedString(@"LOGIN_PSW", nil);
    
    self.phoneNumTF.placeholder = MYLocalizedString(@"LOGIN_MOBILE_PLACEHOLDER", nil);
    self.pswTF.placeholder = MYLocalizedString(@"LOGIN_PSW_PLACEHOLDER", nil);
    
    [self.loginBtn setTitle:MYLocalizedString(@"LOGIN_SUBMIT", nil) forState:UIControlStateNormal];
    [self.countryBtn setTitle:MYLocalizedString(@"LOGIN_PLACE", nil) forState:UIControlStateNormal];
    [self.registerBtn setTitle:MYLocalizedString(@"LOGIN_REGISTER", nil) forState:UIControlStateNormal];
    [self.resetPSWBtn setTitle:MYLocalizedString(@"LOGIN_RESETPSW", nil) forState:UIControlStateNormal];
    self.countryBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self.countryBtn.titleLabel setMinimumScaleFactor:0.5];
    
    self.isHiddenPlayStatusButton = YES;
    
    [self rightBarButton:MYLocalizedString(@"PUBLIC_CANCEL", nil) color:[UIColor whiteColor] selector:@selector(backBtnClick)];
    
    if (ISiPhoneX) {
        self.registerBtnBottom.constant += 34;
    }
    
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    self.phoneNumTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.phoneNumTF.placeholder attributes:@{NSForegroundColorAttributeName : kBGColor}];
    self.pswTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.pswTF.placeholder attributes:@{NSForegroundColorAttributeName : kBGColor}];
    
    self.loginBtn.layer.borderWidth = 1.0f;
    self.loginBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.loginBtn.layer.cornerRadius = 5.0f;
    
    if ([UserManager sharedManager].loginName.length > 0) {
        
        Country *country = [Country new];
        country.code = [UserManager sharedManager].loginCode;
        [self selectedCountry:country];
        
        NSString *loginName = [UserManager sharedManager].loginName;
        
        NSString *psw = [SAMKeychain passwordForService:kKeychainService account:loginName];
        
        self.phoneNumTF.text = loginName;
        self.pswTF.text = psw;
    }
    
}
- (void)backBtnClick {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [MobClick event:@"11_1_2"];
}

- (IBAction)restPSW:(id)sender {
    
    ResetPSWVC *restVC = [ResetPSWVC new];
    restVC.delegate = self;
    restVC.country = self.currentCountry;
    restVC.loginName = self.phoneNumTF.text;
    [self.navigationController pushViewController:restVC animated:YES];
    
    [MobClick event:@"11_1_3"];
}

- (IBAction)registerUser:(id)sender {
    
    RegisterVC *registerVC = [RegisterVC new];
    registerVC.country = self.currentCountry;
    registerVC.loginName = self.phoneNumTF.text;
    registerVC.delegate = self.delegate;
    [self.navigationController pushViewController:registerVC animated:YES];
    [MobClick event:@"11_1_9"];
}

- (IBAction)thirdLoginClick:(UIButton *)sender {
    
    NSString *netType = @"";
    UMSocialPlatformType umType = 0;
    //    （微信：wechat，QQ：qq，新浪：sina，FACEBOOK：facebook）
    switch (sender.tag) {
        case 1: { // 微信
            
            netType = @"wechat";
            umType = UMSocialPlatformType_WechatSession;
            [MobClick event:@"11_1_5"];
        }
            break;
        case 2: {// QQ
            
            netType = @"qq";
            umType = UMSocialPlatformType_QQ;
            [MobClick event:@"11_1_6"];
        }
            break;
        case 3: {// 微博
            
            netType = @"sina";
            umType = UMSocialPlatformType_Sina;
            [MobClick event:@"11_1_7"];
        }
            break;
        case 4: {// Facebook
            
            netType = @"facebook";
            umType = UMSocialPlatformType_Facebook;
            [MobClick event:@"11_1_8"];
        }
            break;
            
        default:
            break;
    }
    
    [ActivityIndicatorView showHUDAddedTo:self.view tintColor:[UIColor whiteColor]];
    
    @weakify(self);
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:umType currentViewController:self completion:^(id result, NSError *error) {
        @strongify(self);
        
        if (error) {
            [ActivityIndicatorView hideHUDAddedTo:self.view];
            [IGUtil showToast:[IGUtil tipFromError:error]];
            return ;
        }
        
        UMSocialUserInfoResponse *resp = result;
        
        NSString *uid = resp.uid ? resp.uid : @"";
        NSString *name = resp.name ? resp.name : @"";
        NSString *iconurl = resp.iconurl ? resp.iconurl : @"";
        NSString *gender = resp.gender ? resp.gender : @"";
        
        NSDictionary *paramsDict = @{@"openid":uid,@"opentype":netType,@"realname":name,@"headimg":iconurl,@"gender":gender};
        
        [NetAPIManager thirdRegisterType:paramsDict block:^(NSString *result, NSError *error) {
            
            [ActivityIndicatorView hideHUDAddedTo:self.view];
            
            if (!error) {
                [IGUtil showToast:result];
                [self backBtnClick];
                
                if ([_delegate respondsToSelector:@selector(loginSuccess)]) {
                    [_delegate loginSuccess];
                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccessNotif object:nil];
            }
        }];
    }];
}

- (IBAction)showPSW:(UIButton *)sender {
    
    
    sender.selected = !sender.selected;
    
    self.pswTF.secureTextEntry = !sender.selected;
    [MobClick event:@"11_0_1"];
}
- (IBAction)selectCountry:(UIButton *)sender {
    
    SelectCountryVC *countryVC = [[SelectCountryVC alloc] init];
    countryVC.delegate = self;
    [countryVC showWithVC:self];
}

- (IBAction)commitBtnClick:(id)sender {
    
    [MobClick event:@"11_1_4"];
    [[IQKeyboardManager sharedManager] resignFirstResponder];
    
    NSString* mobile = [self.phoneNumTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (!self.currentCountry) {
        [IGUtil showToast:MYLocalizedString(@"LOGIN_NOCOUNTRY", nil)];
        return;
    }
    
    if ([IGUtil isStringLenght0:mobile]) {
        [IGUtil showToast:MYLocalizedString(@"LOGIN_NOMOBILE", nil)];
        return;
    }
    if ([IGUtil isStringLenght0:self.pswTF.text]) {
        [IGUtil showToast:MYLocalizedString(@"LOGIN_NOPSW", nil)];
        return;
    }
    
    
    [ActivityIndicatorView showHUDAddedTo:self.view tintColor:[UIColor whiteColor]];
    
    @weakify(self);
    [NetAPIManager phoneLoginWithCountryCode:self.currentCountry.code cellPhone:mobile psw:self.pswTF.text block:^(NSString *result, NSError *error) {
        
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        if (!error) {
            [IGUtil showToast:result];
            [self backBtnClick];
            
            if ([_delegate respondsToSelector:@selector(loginSuccess)]) {
                [_delegate loginSuccess];
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccessNotif object:nil];
        }
    }];
}

#pragma mark -delegate
- (void)selectedCountry:(Country *)country {
    
    [self.countryBtn setTitle:country.code forState:UIControlStateNormal];
    self.countryBtn.selected = YES;
    self.currentCountry = country;
    
    self.contryBtnWidth.constant = 60;
    
    [self.countryBtn setImage:[UIImage imageNamed:@"下拉"] forState:UIControlStateNormal];
    
    CGFloat imageWith = CGRectGetWidth(self.countryBtn.imageView.frame);
    
    CGFloat labelWidth = [IGUtil getSizeContent:country.code width:MAXFLOAT font:FontBold(14)].width;
    
    self.countryBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.countryBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);
}

- (void)resetSuccess:(UIViewController *)vc {
    
    Country *country = [Country new];
    country.code = [UserManager sharedManager].loginCode;
    [self selectedCountry:country];
    
    NSString *loginName = [UserManager sharedManager].loginName;
    
    NSString *psw = [SAMKeychain passwordForService:kKeychainService account:loginName];
    
    self.phoneNumTF.text = loginName;
    self.pswTF.text = psw;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
